package com.kaibes.module.user.safe;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.kaibes.core.base.util.StringUtils;
import com.kaibes.core.spring.proxy.Proxy;
import com.kaibes.module.user.UserService;
import com.kaibes.web.api.ApiLink;
import com.kaibes.web.response.ResponseFactory;

@RestController
@RequestMapping("/users/emails")
public class UserEmailApi {

    @Proxy(false)
    private MailService mailService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserSafeService userSafeService;

    @PostMapping("/safe")
    @ApiLink(value = "已有邮箱，获取邮箱验证码", validated = false)
    public ResponseEntity<Object> safeCode(@RequestAttribute Integer userId, HttpSession session) {
    	if (mailService == null) {
    		return ResponseFactory.postFailure("操作失败，网站未启用邮箱模块，请联系网站管理员");
    	}
    	
        String email = userSafeService.getEmailByUserId(userId);
        if (email == null) {
            return ResponseFactory.postFailure("您还没有绑定过邮箱");
        }

        String emailCode = UUID.randomUUID().toString();
        session.setAttribute(UserSafeRes.EMAIL, email);
        session.setAttribute(UserSafeRes.SAFE_EMAIL_CODE, emailCode);

        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("user", userService.getById(userId));
        dataModel.put(UserSafeRes.SAFE_EMAIL_CODE, emailCode);

        if (mailService.sendTemplateMessage(email, UserSafeRes.SAFE_EMAIL_TEMPLATE, dataModel)) {
            return ResponseFactory.ok("已发送一个验证码到您的邮箱，重复获取会导致前一个验证码失效");
        } else {
            return ResponseFactory.postFailure("操作失败，可能是网站未正确设置邮件模块，请联系网站管理员");
        }
    }

    @PostMapping("/bind")
    @ApiLink(value = "绑定邮箱，获取新邮箱验证码", validated = false)
    public ResponseEntity<Object> bindCode(HttpSession session, @RequestAttribute Integer userId, @RequestBody @Validated UserEmail userEmail) {
        String email = userEmail.getEmail();
        if (userSafeService.countByEmail(email) != 0) {
            return ResponseFactory.postFailure("该邮箱已存在，获取验证码失败！");
        }

        String emailCode = UUID.randomUUID().toString();
        session.setAttribute(UserSafeRes.EMAIL, email);
        session.setAttribute(UserSafeRes.BIND_EMAIL_CODE, emailCode);

        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put(UserSafeRes.BIND_EMAIL_CODE, emailCode);

        if (mailService.sendTemplateMessage(email, UserSafeRes.BIND_EMAIL_TEMPLATE, dataModel)) {
            return ResponseFactory.ok("已发送一个验证码到您的邮箱，重复获取会导致前一个验证码失效");
        } else {
            return ResponseFactory.postFailure("操作失败，可能是网站未正确设置邮件模块，请联系网站管理员");
        }
    }

    @PostMapping("/unbind")
    @ApiLink(value = "解绑邮箱，验证", validated = false)
    public ResponseEntity<Object> unbindCode(@RequestAttribute Integer userId, HttpSession session) {
        String email = userSafeService.getEmailByUserId(userId);
        if (email == null) {
            return ResponseFactory.postFailure("您还没有绑定过邮箱");
        }

        String emailCode = UUID.randomUUID().toString();
        session.setAttribute(UserSafeRes.EMAIL, email);
        session.setAttribute(UserSafeRes.UNBIND_EMAIL_CODE, emailCode);

        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("user", userService.getById(userId));
        dataModel.put(UserSafeRes.UNBIND_EMAIL_CODE, emailCode);

        if (mailService.sendTemplateMessage(email, UserSafeRes.UNBIND_EMAIL_TEMPLATE, dataModel)) {
            return ResponseFactory.ok("已发送一个验证码到您的邮箱，重复获取会导致前一个验证码失效");
        } else {
            return ResponseFactory.postFailure("操作失败，可能是网站未正确设置邮件模块，请联系网站管理员");
        }
    }

    // ====================
    @PutMapping("/email")
    @ApiLink(value = "修改邮箱地址", validated = false)
    public ResponseEntity<Object> putEmail(HttpSession session, @RequestAttribute Integer userId, @RequestBody @Validated UserCode userCode) {
        String email = (String) session.getAttribute(UserSafeRes.EMAIL);
        String oldEmail = userSafeService.getEmailByUserId(userId);
        if (StringUtils.isBlank(oldEmail)) {
            String emailCode = (String) session.getAttribute(UserSafeRes.BIND_EMAIL_CODE);
            if (email == null || emailCode == null) {
                return ResponseFactory.putFailure("邮箱不存在或验证码已失效");
            }
            if (!emailCode.equals(userCode.getCode())) {
                return ResponseFactory.putFailure("验证码错误或者已失效");
            }
            session.removeAttribute(UserSafeRes.EMAIL);
            session.removeAttribute(UserSafeRes.BIND_EMAIL_CODE);
            return ResponseFactory.put(userSafeService.updateEmailByUserId(email, userId), "用户绑定邮箱成功", "用户绑定邮箱失败");
        } else {
            String emailCode = (String) session.getAttribute(UserSafeRes.UNBIND_EMAIL_CODE);
            if (email == null || emailCode == null) {
                return ResponseFactory.putFailure("邮箱不存在或验证码已失效");
            }
            if (!emailCode.equals(userCode.getCode())) {
                return ResponseFactory.putFailure("验证码错误或者已失效");
            }

            session.removeAttribute(UserSafeRes.EMAIL);
            session.removeAttribute(UserSafeRes.UNBIND_EMAIL_CODE);

            if (oldEmail.equals(email)) {
                return ResponseFactory.put(userSafeService.updateEmailByUserId("", userId), "用户解绑邮箱成功", "用户解绑邮箱失败");
            } else {
                return ResponseFactory.putFailure("邮箱地址不正确");
            }
        }
    }

    @PutMapping("/info")
    @ApiLink(value = "修改安全信息", validated = false)
    public ResponseEntity<Object> putSelf(HttpSession session, @RequestAttribute Integer userId,
            @RequestBody @Validated UserSafeUpdateSelf data) {
        String email = (String) session.getAttribute(UserSafeRes.EMAIL);
        String emailCode = (String) session.getAttribute(UserSafeRes.SAFE_EMAIL_CODE);
        String temp = userSafeService.getEmailByUserId(userId);
        if (email == null || emailCode == null || !email.equals(temp)) {
            return ResponseFactory.putFailure("邮箱不存在或验证码已失效");
        }
        if (!emailCode.equals(data.getCode())) {
            return ResponseFactory.putFailure("验证码错误或者已失效");
        }
        session.removeAttribute(UserSafeRes.EMAIL);
        session.removeAttribute(UserSafeRes.SAFE_EMAIL_CODE);

        if (StringUtils.isBlank(data.getQuestion())) {
            data.setQuestion(null);
        }
        if (StringUtils.isBlank(data.getAnswer())) {
            data.setAnswer(null);
        }
        return ResponseFactory.put(userSafeService.updateByUserId(data, userId), "用户修改安全信息成功", "用户修改安全信息失败");
    }

    // =========================
    @PostMapping("/email")
    @ApiLink(value = "绑定邮箱地址", validated = false)
    public ResponseEntity<Object> postEmail(HttpSession session, @RequestAttribute Integer userId,
            @RequestBody @Validated UserCode userCode) {
        String email = (String) session.getAttribute(UserSafeRes.EMAIL);
        String emailCode = (String) session.getAttribute(UserSafeRes.BIND_EMAIL_CODE);
        if (email == null || emailCode == null) {
            return ResponseFactory.putFailure("邮箱不存在或验证码已失效");
        }
        if (!emailCode.equals(userCode.getCode())) {
            return ResponseFactory.putFailure("验证码错误或者已失效");
        }
        session.removeAttribute(UserSafeRes.EMAIL);
        session.removeAttribute(UserSafeRes.BIND_EMAIL_CODE);

        return ResponseFactory.put(userSafeService.updateEmailByUserId(email, userId), "用户绑定邮箱成功", "用户绑定邮箱失败");
    }

    @DeleteMapping("/email")
    @ApiLink(value = "解绑邮箱地址", validated = false)
    public ResponseEntity<Object> deleteEmail(HttpSession session, @RequestAttribute Integer userId,
            @RequestBody @Validated UserCode userCode) {
        String email = (String) session.getAttribute(UserSafeRes.EMAIL);
        String emailCode = (String) session.getAttribute(UserSafeRes.UNBIND_EMAIL_CODE);
        if (email == null || emailCode == null) {
            return ResponseFactory.putFailure("邮箱不存在或验证码已失效");
        }
        if (!emailCode.equals(userCode.getCode())) {
            return ResponseFactory.putFailure("验证码错误或者已失效");
        }

        session.removeAttribute(UserSafeRes.EMAIL);
        session.removeAttribute(UserSafeRes.UNBIND_EMAIL_CODE);

        String oldEmail = userSafeService.getEmailByUserId(userId);
        if (StringUtils.isBlank(oldEmail)) {
            return ResponseFactory.putFailure("您还没有绑定过邮箱");
        } else {
            if (oldEmail.equals(email)) {
                return ResponseFactory.put(userSafeService.updateEmailByUserId("", userId), "用户解绑邮箱成功", "用户解绑邮箱失败");
            } else {
                return ResponseFactory.putFailure("邮箱地址不正确");
            }
        }
    }
}
